package com.devplatform.util;

import cn.hutool.core.util.RandomUtil;
import com.devplatform.constants.DataVoCodeConstant;
import com.devplatform.pojo.EmailCode;
import com.devplatform.pojo.vo.DataVo;
import com.devplatform.service.EmailCodeService;
import jakarta.mail.internet.MimeMessage;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@RequiredArgsConstructor
@Log4j2
public class EmailUtil {
    private final JavaMailSender mailSender;
    private final EmailCodeService emailCodeService;


    @Value("${spring.mail.username}")
    private String from;
    @Value("${mail.timeout}")
    private int timeout;
    @Value("${mail.subject}")
    private String subject;
    @Value("${mail.timeout}")
    private int mailTimeout;

    public String sendMail(String email) {
        String code = RandomUtil.randomString(6);

        String content = "您的验证码是：" + code + "," + (timeout / 60) + "分钟内有效";
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            //邮件设置
            helper.setFrom(from);
            //接收人
            helper.setTo(email);
            //标题与内容
            helper.setSubject(subject);
            helper.setText(content);
            mailSender.send(mimeMessage);
            return code;
        } catch (Exception e) {
            log.error("验证码发送失败:{}", e.getMessage());
            return null;
        }
    }

    //判断邮箱验证码的方法，返回dataVo，如果验证正确则返回null
    public DataVo checkEmailCode(HttpSession session, String email, String inEmailCode) {
        EmailCode emailCode = emailCodeService.getById(session.getId());
        if (emailCode == null || !emailCode.getEmail().equals(email)) {
            return DataVo.error(DataVoCodeConstant.EMAIL_CODE_IS_NULL, "未发送邮件验证码");
        }
        if (emailCode.getSendTime().plusSeconds(mailTimeout).isBefore(LocalDateTime.now())) {
            return DataVo.error(DataVoCodeConstant.EMAIL_CODE_EXPIRED, "邮件验证码已过期");
        }
        //转换小写比较
        String userInCode = inEmailCode.toLowerCase();
        if (!emailCode.getCode().toLowerCase().equals(userInCode)) {
            return DataVo.error(DataVoCodeConstant.EMAIL_CODE_ERROR, "邮件验证码错误");
        }
        return null;
    }

}
